<template>
  <div class="dispatch-container">
    <!-- 顶部统计面板 -->
    <div class="stats-panel">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ stats.onlineVehicles }}</div>
              <div class="stats-label">在线车辆</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ stats.pendingOrders }}</div>
              <div class="stats-label">待调度订单</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ stats.busyVehicles }}</div>
              <div class="stats-label">忙碌车辆</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ stats.averageResponseTime }}s</div>
              <div class="stats-label">平均响应时间</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <el-row :gutter="20" style="height: 100%">
        <!-- 左侧地图区域 -->
        <el-col :span="16">
          <el-card class="map-card">
            <template #header>
              <div class="card-header">
                <span>实时调度地图</span>
                <div class="map-controls">
                  <el-button-group>
                    <el-button 
                      :type="mapMode === 'vehicles' ? 'primary' : 'default'"
                      @click="toggleMapMode('vehicles')"
                    >
                      显示车辆
                    </el-button>
                    <el-button 
                      :type="mapMode === 'orders' ? 'primary' : 'default'"
                      @click="toggleMapMode('orders')"
                    >
                      显示订单
                    </el-button>
                    <el-button 
                      :type="mapMode === 'all' ? 'primary' : 'default'"
                      @click="toggleMapMode('all')"
                    >
                      显示全部
                    </el-button>
                  </el-button-group>
                  <el-button @click="refreshMap" :loading="mapLoading">
                    <Icon icon="ep:refresh" />
                    刷新
                  </el-button>
                </div>
              </div>
            </template>
            <div id="amap-container" class="map-container"></div>
          </el-card>
        </el-col>

        <!-- 右侧操作面板 -->
        <el-col :span="8">
          <el-card class="operation-card">
            <template #header>
              <div class="card-header">
                <span>调度操作</span>
                <el-button @click="autoDispatchAll" type="primary" size="small">
                  自动调度全部
                </el-button>
              </div>
            </template>
            
            <!-- 待调度订单列表 -->
            <div class="pending-orders">
              <h4>待调度订单</h4>
              <div class="order-list">
                <div 
                  v-for="order in pendingOrders" 
                  :key="order.id"
                  class="order-item"
                  :class="{ 'selected': selectedOrder?.id === order.id }"
                  @click="selectOrder(order)"
                >
                  <div class="order-header">
                    <span class="order-no">{{ order.orderNo }}</span>
                    <span class="order-time">{{ formatTime(order.createTime) }}</span>
                  </div>
                  <div class="order-info">
                    <div class="passenger-info">
                      <Icon icon="ep:user" />
                      {{ order.passengerName }}
                    </div>
                    <div class="route-info">
                      <div class="start-point">
                        <Icon icon="ep:location" class="start-icon" />
                        {{ order.startAddress }}
                      </div>
                      <div class="end-point">
                        <Icon icon="ep:location" class="end-icon" />
                        {{ order.endAddress }}
                      </div>
                    </div>
                    <div class="order-meta">
                      <span class="distance">{{ order.distance }}km</span>
                      <span class="price">¥{{ order.estimatedPrice }}</span>
                    </div>
                  </div>
                  <div class="order-actions">
                    <el-button size="small" @click.stop="autoDispatchOrder(order.id)">
                      自动调度
                    </el-button>
                    <el-button size="small" type="primary" @click.stop="showManualDispatch(order)">
                      手动分配
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 在线车辆列表 -->
            <div class="online-vehicles" v-if="selectedOrder">
              <h4>附近车辆</h4>
              <div class="vehicle-list">
                <div 
                  v-for="vehicle in nearbyVehicles" 
                  :key="vehicle.id"
                  class="vehicle-item"
                  @click="assignOrderToVehicle(selectedOrder.id, vehicle.driverId)"
                >
                  <div class="vehicle-info">
                    <span class="plate-no">{{ vehicle.plateNo }}</span>
                    <span class="distance">{{ calculateDistance(selectedOrder, vehicle) }}km</span>
                  </div>
                  <div class="vehicle-status">
                    <el-tag :type="getVehicleStatusType(vehicle.status)" size="small">
                      {{ getVehicleStatusText(vehicle.status) }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 手动分配对话框 -->
    <el-dialog v-model="manualDispatchVisible" title="手动分配订单" width="600px">
      <div v-if="currentOrder">
        <h4>订单信息</h4>
        <p><strong>订单号：</strong>{{ currentOrder.orderNo }}</p>
        <p><strong>乘客：</strong>{{ currentOrder.passengerName }}</p>
        <p><strong>起点：</strong>{{ currentOrder.startAddress }}</p>
        <p><strong>终点：</strong>{{ currentOrder.endAddress }}</p>
        
        <h4>选择司机</h4>
        <el-table :data="availableDrivers" @row-click="selectDriver">
          <el-table-column prop="plateNo" label="车牌号" width="120" />
          <el-table-column prop="driverName" label="司机姓名" width="120" />
          <el-table-column prop="distance" label="距离" width="80">
            <template #default="{ row }">
              {{ row.distance }}km
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="getVehicleStatusType(row.status)" size="small">
                {{ getVehicleStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="confirmAssignment(row)">
                分配
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Icon } from '@/components/Icon'
import { DispatchApi, type VehicleLocationVO, type OrderVO, type DispatchStatsVO } from '@/api/ride/dispatch'

// 响应式数据
const stats = ref<DispatchStatsVO>({
  totalVehicles: 0,
  onlineVehicles: 0,
  busyVehicles: 0,
  totalOrders: 0,
  pendingOrders: 0,
  completedOrders: 0,
  averageResponseTime: 0,
  totalRevenue: 0
})

const pendingOrders = ref<OrderVO[]>([])
const vehicleLocations = ref<VehicleLocationVO[]>([])
const nearbyVehicles = ref<VehicleLocationVO[]>([])
const availableDrivers = ref<any[]>([])
const selectedOrder = ref<OrderVO | null>(null)
const currentOrder = ref<OrderVO | null>(null)
const mapMode = ref<'vehicles' | 'orders' | 'all'>('all')
const mapLoading = ref(false)
const manualDispatchVisible = ref(false)

// 高德地图相关
let map: any = null
let vehicleMarkers: any[] = []
let orderMarkers: any[] = []
let refreshTimer: any = null

// 初始化高德地图
const initAMap = async () => {
  try {
    // 动态加载高德地图API
    await loadAMapScript()
    
    map = new (window as any).AMap.Map('amap-container', {
      zoom: 12,
      center: [116.397428, 39.90923], // 北京坐标
      mapStyle: 'amap://styles/normal'
    })

    // 添加地图控件
    map.addControl(new (window as any).AMap.Scale())
    map.addControl(new (window as any).AMap.ToolBar())
    
    // 加载数据
    await loadMapData()
    
  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage.error('地图初始化失败，请检查网络连接')
  }
}

// 动态加载高德地图脚本
const loadAMapScript = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    if ((window as any).AMap) {
      resolve()
      return
    }
    
    const script = document.createElement('script')
    script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=YOUR_AMAP_KEY&plugin=AMap.Scale,AMap.ToolBar'
    script.onload = () => resolve()
    script.onerror = () => reject(new Error('高德地图API加载失败'))
    document.head.appendChild(script)
  })
}

// 加载地图数据
const loadMapData = async () => {
  try {
    mapLoading.value = true
    
    // 并行加载数据
    const [statsRes, ordersRes, vehiclesRes] = await Promise.all([
      DispatchApi.getDispatchStats(),
      DispatchApi.getPendingOrders(),
      DispatchApi.getVehicleLocations()
    ])
    
    stats.value = statsRes.data
    pendingOrders.value = ordersRes.data
    vehicleLocations.value = vehiclesRes.data
    
    // 更新地图标记
    updateMapMarkers()
    
  } catch (error) {
    console.error('数据加载失败:', error)
    ElMessage.error('数据加载失败')
  } finally {
    mapLoading.value = false
  }
}

// 更新地图标记
const updateMapMarkers = () => {
  if (!map) return
  
  // 清除现有标记
  clearMarkers()
  
  // 添加车辆标记
  if (mapMode.value === 'vehicles' || mapMode.value === 'all') {
    addVehicleMarkers()
  }
  
  // 添加订单标记
  if (mapMode.value === 'orders' || mapMode.value === 'all') {
    addOrderMarkers()
  }
}

// 添加车辆标记
const addVehicleMarkers = () => {
  vehicleLocations.value.forEach(vehicle => {
    const marker = new (window as any).AMap.Marker({
      position: [vehicle.longitude, vehicle.latitude],
      icon: getVehicleIcon(vehicle.status),
      title: `${vehicle.plateNo} - ${getVehicleStatusText(vehicle.status)}`
    })
    
    // 添加点击事件
    marker.on('click', () => {
      showVehicleInfo(vehicle)
    })
    
    map.add(marker)
    vehicleMarkers.push(marker)
  })
}

// 添加订单标记
const addOrderMarkers = () => {
  pendingOrders.value.forEach(order => {
    // 起点标记
    const startMarker = new (window as any).AMap.Marker({
      position: [order.startLongitude, order.startLatitude],
      icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
      title: `起点: ${order.startAddress}`
    })
    
    // 终点标记
    const endMarker = new (window as any).AMap.Marker({
      position: [order.endLongitude, order.endLatitude],
      icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
      title: `终点: ${order.endAddress}`
    })
    
    // 添加点击事件
    startMarker.on('click', () => {
      selectOrder(order)
    })
    
    map.add([startMarker, endMarker])
    orderMarkers.push(startMarker, endMarker)
  })
}

// 清除地图标记
const clearMarkers = () => {
  if (vehicleMarkers.length > 0) {
    map.remove(vehicleMarkers)
    vehicleMarkers = []
  }
  if (orderMarkers.length > 0) {
    map.remove(orderMarkers)
    orderMarkers = []
  }
}

// 获取车辆图标
const getVehicleIcon = (status: number) => {
  const iconMap = {
    0: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png', // 离线 - 红色
    1: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_g.png', // 在线 - 绿色
    2: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'  // 忙碌 - 蓝色
  }
  return iconMap[status] || iconMap[0]
}

// 切换地图显示模式
const toggleMapMode = (mode: 'vehicles' | 'orders' | 'all') => {
  mapMode.value = mode
  updateMapMarkers()
}

// 刷新地图
const refreshMap = async () => {
  await loadMapData()
}

// 选择订单
const selectOrder = (order: OrderVO) => {
  selectedOrder.value = order
  
  // 查找附近车辆
  nearbyVehicles.value = vehicleLocations.value
    .filter(vehicle => vehicle.status === 1) // 只显示在线车辆
    .map(vehicle => ({
      ...vehicle,
      distance: calculateDistance(order, vehicle)
    }))
    .sort((a, b) => a.distance - b.distance)
    .slice(0, 5) // 只显示最近的5辆车
}

// 显示手动分配对话框
const showManualDispatch = (order: OrderVO) => {
  currentOrder.value = order
  availableDrivers.value = nearbyVehicles.value
  manualDispatchVisible.value = true
}

// 自动调度单个订单
const autoDispatchOrder = async (orderId: number) => {
  try {
    await DispatchApi.autoDispatch(orderId)
    ElMessage.success('自动调度成功')
    await loadMapData()
  } catch (error) {
    ElMessage.error('自动调度失败')
  }
}

// 自动调度全部订单
const autoDispatchAll = async () => {
  try {
    const result = await ElMessageBox.confirm(
      '确定要自动调度所有待分配订单吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (result === 'confirm') {
      // 这里应该调用批量自动调度API
      for (const order of pendingOrders.value) {
        await DispatchApi.autoDispatch(order.id)
      }
      ElMessage.success('批量自动调度完成')
      await loadMapData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量调度失败')
    }
  }
}

// 分配订单给车辆
const assignOrderToVehicle = async (orderId: number, driverId: number) => {
  try {
    await DispatchApi.assignOrder({
      orderId,
      driverId,
      operationType: 1, // 手动分配
      reason: '手动分配'
    })
    ElMessage.success('订单分配成功')
    selectedOrder.value = null
    await loadMapData()
  } catch (error) {
    ElMessage.error('订单分配失败')
  }
}

// 确认分配
const confirmAssignment = async (driver: any) => {
  if (!currentOrder.value) return
  
  await assignOrderToVehicle(currentOrder.value.id, driver.driverId)
  manualDispatchVisible.value = false
}

// 选择司机
const selectDriver = (driver: any) => {
  // 可以在这里添加选择逻辑
}

// 显示车辆信息
const showVehicleInfo = (vehicle: VehicleLocationVO) => {
  // 可以显示车辆详细信息弹窗
  console.log('车辆信息:', vehicle)
}

// 计算距离（简化版本，实际应该使用地图API计算）
const calculateDistance = (order: OrderVO, vehicle: VehicleLocationVO): number => {
  const lat1 = order.startLatitude
  const lon1 = order.startLongitude
  const lat2 = vehicle.latitude
  const lon2 = vehicle.longitude
  
  const R = 6371 // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180
  const dLon = (lon2 - lon1) * Math.PI / 180
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  const distance = R * c
  
  return Math.round(distance * 10) / 10 // 保留一位小数
}

// 获取车辆状态类型
const getVehicleStatusType = (status: number) => {
  const typeMap = {
    0: 'danger',  // 离线
    1: 'success', // 在线
    2: 'warning'  // 忙碌
  }
  return typeMap[status] || 'info'
}

// 获取车辆状态文本
const getVehicleStatusText = (status: number) => {
  const textMap = {
    0: '离线',
    1: '在线',
    2: '忙碌'
  }
  return textMap[status] || '未知'
}

// 格式化时间
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 生命周期
onMounted(async () => {
  await nextTick()
  await initAMap()
  
  // 设置定时刷新
  refreshTimer = setInterval(() => {
    loadMapData()
  }, 30000) // 30秒刷新一次
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  if (map) {
    map.destroy()
  }
})
</script>

<style scoped>
.dispatch-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #f5f5f5;
}

.stats-panel {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-item {
  padding: 10px;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

.main-content {
  flex: 1;
  min-height: 0;
}

.map-card,
.operation-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.map-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.map-container {
  height: 500px;
  width: 100%;
}

.pending-orders,
.online-vehicles {
  margin-bottom: 20px;
}

.pending-orders h4,
.online-vehicles h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
}

.order-list,
.vehicle-list {
  max-height: 300px;
  overflow-y: auto;
}

.order-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.order-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.order-item.selected {
  border-color: #409eff;
  background-color: #f0f8ff;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.order-no {
  font-weight: bold;
  color: #409eff;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.passenger-info {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 5px;
  font-size: 14px;
}

.route-info {
  margin-bottom: 8px;
}

.start-point,
.end-point {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  margin-bottom: 3px;
}

.start-icon {
  color: #67c23a;
}

.end-icon {
  color: #f56c6c;
}

.order-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.price {
  color: #e6a23c;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 8px;
}

.vehicle-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.vehicle-item:hover {
  border-color: #409eff;
  background-color: #f0f8ff;
}

.vehicle-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.plate-no {
  font-weight: bold;
  color: #333;
}

.distance {
  font-size: 12px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content .el-col:first-child {
    margin-bottom: 20px;
  }
}
</style>